package com.test.blogsystem.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.blogsystem.Comment.Exception.BlogException;
import com.test.blogsystem.Mapper.BlogMapper;
import com.test.blogsystem.Mapper.UserMapper;
import com.test.blogsystem.Pojo.DO.BlogInfo;
import com.test.blogsystem.Pojo.DO.UserInfo;
import com.test.blogsystem.Pojo.Require.LoginInfo;
import com.test.blogsystem.Pojo.Response.UserInfoResponse;
import com.test.blogsystem.Pojo.Response.UserLoginResponse;
import com.test.blogsystem.Service.UserService;
import com.test.blogsystem.Utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public UserLoginResponse checkPassword(LoginInfo loginInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, loginInfo.getUserName()).eq(UserInfo::getDeleteFlag, 0);
        UserInfo userInfo = userMapper.selectOne(queryWrapper);

        if (userInfo == null) {
            throw new BlogException("用户未存在...", 0);
        }
        if (!loginInfo.getPassword().equals(userInfo.getPassword())) {
            throw new BlogException("密码错误...", -1);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("name", userInfo.getUserName());
        String key = JWTUtil.getKey(map);
        return new UserLoginResponse(userInfo.getId(), key);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0).eq(UserInfo::getId,userId);
        UserInfo userInfo = userMapper.selectOne(queryWrapper);
        log.info("userInfo: {}",userInfo);

        UserInfoResponse userInfoResponse = new UserInfoResponse();
        BeanUtils.copyProperties(userInfo,userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        QueryWrapper<BlogInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BlogInfo::getDeleteFlag,0).eq(BlogInfo::getId,blogId);
        BlogInfo blogInfo = blogMapper.selectOne(queryWrapper);

        log.info("blogInfo:{}",blogInfo);
        return getUserInfo(blogInfo.getUserId());
    }


}
